import { Button, Form, Input, Row, Col, Select } from "antd";
import { DownOutlined, UpOutlined } from "@ant-design/icons";
import React, { useState, forwardRef, useLayoutEffect } from "react";
const CommonForm = forwardRef((props, ref) => {
    const [expand, setExpand] = useState(false);
    const [form] = Form.useForm();
    const onExpand = () => {
        setExpand(!expand);
    };
    useLayoutEffect(() => {
        var myEvent = new Event("resize");
        window.dispatchEvent(myEvent);
    return () => {};
}, [expand]);
const getFields = () => {
    const formList = props.formList;
    const count = expand ? formList.length : 6;
    const children = [];
    for (let i = 0; i < count; i++) {
        children.push(
            <Col span={8} key={i}>
                <Form.Item
            name={formList[i].name}
            label={formList[i].label}
            rules={
                props.rules
                ? props.rules
                : [
                    {
                        required: true,
                        message:
                        formList[i].type === "select"
                        ? "请选择"
                          : "请输入" + formList[i].label,
                        },
                    ]
                }
              >
                {formList[i].type === "select" ? (
                    <Select defaultValue="2">
                        {formList[i].options.map((item) => {
            return <Option value={item.value}>{item.label}</Option>;
        })}
        </Select>
                   ) : "render" in formList[i] ? (formList[i].render(formList[i])
                   ) : (
                    <Input placeholder={"请输入" + formList[i].label} />
                    )}
                    </Form.Item>
        </Col>
      );
    }
    return children;
  };
  return (
    <Form form={form} initialValues={props.value} onValuesChange={props.change}>
     <Row gutter={24}>{getFields()}</Row>
     <Row>
        <Col span={24} style={{ textAlign: "right" }}>
          <Button type="primary" htmlType="submit">
            Search
            </Button>
          <Button
            style={{ margin: "0 8px" }}
            onClick={() => {
                form.resetFields();
            }}
          >
            Clear
          </Button>
          <a style={{ fontSize: 12 }} onClick={onExpand}>
          {expand ? <UpOutlined /> : <DownOutlined />} Collapse
          </a>
        </Col>
      </Row>
    </Form>
  );
});
export default CommonForm;